package com.threeox.httplibrary.request;

import com.threeox.httplibrary.OkHttpUtils;
import com.threeox.httplibrary.callback.Callback;
import com.threeox.httplibrary.utils.Exceptions;

import java.io.File;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 *
 * @ClassName: PostFileRequest
 *
 * @Description: Todo(PostFile多个文件请求方式)
 *
 * @author 赵屈犇
 *
 * @date 创建时间:2016/12/21 11:25
 *
 * @version 1.0
 */
public class PostMultiFileRequest extends OkHttpRequest {

    private static MediaType MEDIA_TYPE_STREAM = MediaType.parse("application/octet-stream");
    private File[] files;
    private MediaType mediaType;

    public PostMultiFileRequest(String url, Object tag, Map<String, Object> params, Map<String, Object> headers, MediaType mediaType, int id, File... file) {
        super(url, tag, params, headers,id);
        this.files = file;
        this.mediaType = mediaType;
        if (this.files == null) {
            Exceptions.illegalArgument("文件不能为空!");
        }
        if (this.mediaType == null) {
            this.mediaType = MEDIA_TYPE_STREAM;
        }
    }

    @Override
    protected RequestBody buildRequestBody() {
        return null;
    }

    @Override
    protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback) {
        if (callback == null) return requestBody;

        if (this.files != null && this.files.length > 0) {
            String boundary = "xx--------------------------------------------------------------xx";
            MultipartBody.Builder builder = new MultipartBody.Builder(boundary).setType(MultipartBody.FORM);
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                builder.addFormDataPart("file", file.getAbsolutePath(), RequestBody.create(mediaType, file));
            }
            return builder.build();
        }
        return null;
    }

    @Override
    protected Request buildRequest(RequestBody requestBody) {
        return builder.post(requestBody).build();
    }



}
